package com.loveyukari.service;

import com.loveyukari.dao.ManageAuthDao;
import com.loveyukari.model.Auth;
import com.loveyukari.model.ManageAuth;
import com.loveyukari.utils.AESUtils;
import com.loveyukari.utils.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class ManagerService {



    @Autowired
    private ManageAuthDao manageAuthDao;

    private Logger logger = LoggerFactory.getLogger(ManagerService.class);

    private List<ManageAuth> manageAuthList;

    private static Map<String,ManageAuth> signManagerMap;

    private static final String PHONE_AES_KEY = "qewjcn4cn3$9^1e!cvjsd;f`134sdkv03";


    public int getManageAuthority(String sign){
        ManageAuth manageAuth = signManagerMap.get(sign);
        if (manageAuth == null){
            return 1000;
        }
        return manageAuth.getAuthority();
    }

    public ManageAuth getManageAuthBySign(String sign){
        if (signManagerMap == null){
            reloadManger();
        }
        return signManagerMap.get(sign);
    }

    public int getManageAuthId(String sign){
        ManageAuth manageAuth = signManagerMap.get(sign);
        if (manageAuth == null){
            return -1;
        }
        Integer authId = manageAuth.getAuthId();
        if (authId == null){
            return -1;
        }
        return authId;
    }

    public boolean isLogin(String phone){
        reloadManger();
        for (ManageAuth manageAuth :
                manageAuthList) {
            if (StringUtils.equals(manageAuth.getPhone(), phone)) {
                return true;
            }
        }
        return false;
    }

    public void reloadManger(){
        List<ManageAuth> list = manageAuthDao.selectAll();
        HashMap<String, ManageAuth> map = new HashMap<>();
        for (ManageAuth manageAuth:
             list) {
            try {
                String sign = getSign(manageAuth);
                map.put(sign,manageAuth);
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
        manageAuthList = list;
        signManagerMap = map;
    }


    public String getSign(String phone) throws Exception {
        ManageAuth manageAuth = manageAuthDao.selectByPhone(phone);
        return getSign(manageAuth);
    }

    public String getSign(ManageAuth manageAuth) throws Exception {
        String sign = AESUtils.encrypt(manageAuth.getPhone()+manageAuth.getAuthority(), PHONE_AES_KEY);
        sign = MD5Utils.md5String32(sign);
        return sign;
    }




}
